
//游戏
class Game{
  constructor(box,that){
    that = this;
    this.box = box;
    this.food = new Food(this.box);
    this.snake = new Snake(this.box);
    window.that = that;
  }
  gameStart(){
    this.food.create(this.box);
    this.snake.create(this.box);
    this.runSnake(this.box);
    this.bindKey(this.snake);
  }

  runSnake(box){
    let that = this;
    var timer = setInterval(() => {
      that.snake.run();
      that.snake.remove(that.box);
      that.snake.create(that.box);

      var maxX = that.box.offsetWidth / that.snake.width;
      var maxY = that.box.offsetHeight / that.snake.height;

      // 找到当前蛇头的位置
      var headX = that.snake.body[0].x;
      var headY = that.snake.body[0].y;
      // 蛇头的具体位置
      let hX = headX * that.snake.width;
      let hY = headY * that.snake.height;
      for(var i = 0; i < that.food.elements.length; i++){
        if(hX == that.food.elements[i].offsetLeft && hY == that.food.elements[i].offsetTop){
          //吃到食物
          // 删除食物
          that.food.remove(that.box, i);
          that.food.create(that.box);

          // 添加一个新的蛇节
          var last = that.snake.body[that.snake.body.length - 1];

          that.snake.body.push({
            x: last.x,
            y: last.y,
            color: last.color
          });
        }
      }
      


      if (headX < 0 || headX >= maxX || headY < 0 || headY >= maxY) {
        // 停止定时器
        clearInterval(timer);
        // 弹出提醒
        alert("Game over");
      }
    }, 200);
  }
  bindKey(snake){
    // 给文档绑定键盘按下事件
    document.onkeydown = function (e) {
      // console.log(e.keyCode);
      // 键盘的编码
      // 37 -- left
      // 38 -- top
      // 39 -- right
      // 40 -- bottom
      switch (e.keyCode) {
        case 37:
          snake.direction = "left";
          break;
        case 38:
          snake.direction = "top";
          break;
        case 39:
          snake.direction = "right";
          break;
        case 40:
          snake.direction = "bottom";
          break;
      }
    };
  }
}
let that;
let box = document.getElementById("box");
let game = new Game(box,that);
game.gameStart();
